package com.ygl.controller;

import com.github.pagehelper.PageInfo;
import com.ygl.entity.User;
import com.ygl.service.UserService;
import com.ygl.utils.RequestUtils;
import com.ygl.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author ygl
 * @date 2021/7/8
 * @description xxx
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/create")
    public Result create(@RequestBody User user) {
        userService.create(user);
        return Result.ok(user);
    }

    @GetMapping("/delete")
    public Result delete(@RequestParam Integer id) {
        userService.delete(id);
        return Result.ok();
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.ok(user);
    }

    @PostMapping("/query")
    public Map query(@RequestBody User user) {
        System.out.println("user" + user);
        PageInfo<User> pageInfo = userService.query(user);
        return Result.ok(pageInfo, "操作成功");
    }

    @PostMapping("/detail")
    public Result detail(Integer id) {
        User user = userService.detail(id);
        return Result.ok(user);
    }

    @PostMapping("/count")
    public Result count(@RequestBody User user) {
        Integer count = userService.count(user);
        return Result.ok(count);
    }

    // 注明接收到的是文件
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        //读取后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        String newFileNamePrefix = UUID.randomUUID().toString();
        String newFileName = newFileNamePrefix + "." + ext;
        multipartFile.transferTo(new File("E:\\YglBlogSpringBootVue\\upload", newFileName));
        //最后返回一个可以访问的全路径
        return Result.ok(RequestUtils.getBasePath(request) + "upload/" + newFileName);
    }
}
